package com.taoz.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taoz.usercenter.constant.UserConstant;
import com.taoz.usercenter.exception.BusinessError;
import com.taoz.usercenter.exception.BusinessException;
import com.taoz.usercenter.model.domain.User;
import com.taoz.usercenter.model.request.UserLoginRequest;
import com.taoz.usercenter.model.request.UserRegisterRequest;
import com.taoz.usercenter.model.response.BaseResponse;
import com.taoz.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户接口
 *
 * @author taoz
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    // 用户注册
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(BusinessError.EXIST_EMPTY_PARAMS);
        }

        Long id = userService.userRegister(userAccount, userPassword, checkPassword);

        return BaseResponse.success(id);
    }

    // 用户登录
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest httpServletRequest) {
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            log.info("userAccount or userPassword is not valid!");
            throw new BusinessException(BusinessError.EXIST_EMPTY_PARAMS);
        }

        log.info("Checking is a valid User ?");

        User user = userService.userLogin(userAccount, userPassword, httpServletRequest);

        return BaseResponse.success(user);
    }

    // 用户登出
    @PostMapping("/logout")
    public BaseResponse<String> logout(HttpServletRequest request) {
        userService.logout(request);

        return BaseResponse.success("Logout Success !");
    }

    // 判断是否为管理员
    public Boolean isAdmin(HttpServletRequest httpServletRequest) {
        Object userLoginState = httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (userLoginState == null) {
            return false;
        }
        User user = (User) userLoginState;
        Integer userRole = user.getUserRole();
        return userRole.equals(UserConstant.ADMIN_USER);
    }

    // 判断是否为合法用户，普通用户，管理员为合法
    public Boolean isValidUser(HttpServletRequest request) {
        return request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) != null;
    }

    // 查询指定id的用户
    @GetMapping("/getCurrentUser")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        if (!isValidUser(request)) {
            throw new BusinessException(BusinessError.NO_LOGIN);
        }

        Object o = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        User user = (User) o;
        user = userService.getById(user.getId());

        if (user == null) {
            throw new BusinessException(BusinessError.NO_USER_WITH_SUCH_ID);
        }

        userService.makeUserInsensitive(user);

        return BaseResponse.success(user);
    }

    // 返回所有用户
    @GetMapping("/getUserList")
    public BaseResponse<List<User>> getUserList(HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(BusinessError.NO_ADMIN);
        }

        return BaseResponse.success(userService.list());
    }

    // 模糊查询，查询包含username的用户
    @GetMapping("/searchByUsername")
    public BaseResponse<List<User>> searchByUsername(String username, HttpServletRequest httpServletRequest) {
        // 只允许管理员用户访问该接口
        if (!isAdmin(httpServletRequest)) {
            throw new BusinessException(BusinessError.NO_ADMIN);
        }

        if (username == null) {
            log.info("username is not valid !");
            throw new BusinessException(BusinessError.EXIST_EMPTY_PARAMS);
        }

        if (username.length() < 4) {
            throw new BusinessException(BusinessError.PARAMS_LENGTH_INVALID);
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username", username);
        List<User> userList = userService.list(queryWrapper);
        // 脱敏后返回
        for (User user : userList) {
            userService.makeUserInsensitive(user);
        }

        return BaseResponse.success(userList);
    }

    // 根据指定id删除对应的用户
    @GetMapping("/deleteUserById")
    public BaseResponse<Boolean> deleteUserById(Integer id, HttpServletRequest httpServletRequest) {
        // 只有管理员有权限删除用户
        if (!isAdmin(httpServletRequest)) {
            log.info("No Permission !");
            throw new BusinessException(BusinessError.NO_ADMIN);
        }

        // 传入的id只有 > 0 时合法
        if (id == null || id < 0) {
            log.info("Invalid Id !");
            throw new BusinessException(BusinessError.ID_MUST_BE_POSITIVE_INT);
        }

        log.info("Ready To Delete User, id: " + id);

        boolean success = userService.removeById(id);

        if (success) {
            return BaseResponse.success(true);
        }
        throw new BusinessException(BusinessError.REMOVE_USER_BY_ID_FAILED);
    }
}
